package org.mech.sefer.service.rmi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;

/**
 * <p>
 * The RmiProxyFactoryBeanFactory exports RmiProxyFactoryBean to spring context.
 * </p>
 * <p>
 * Date: 24.5.2012 12:56:46
 * </p>
 * 
 * @author martin.krajc
 */
public class RmiProxyFactoryBeanFactory extends AbstractRmiBeanDefinitionRegistrator {

	/**
	 * The logger.
	 */
	private final Logger logger = LoggerFactory.getLogger(RmiProxyFactoryBeanFactory.class);

	/**
	 * The remote invocation factory reference.
	 */
	private String remoteInvocationFactoryRef;

	/**
	 * The rmi url.
	 */
	private String rmiUrl;

	public String getRemoteInvocationFactoryRef() {
		return remoteInvocationFactoryRef;
	}

	public String getRmiUrl() {
		return rmiUrl;
	}
		
	@Override
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		this.rmiUrl = new StringBuilder("rmi://").append(getHost()).append(":").append(getRmiRegistryPort()).append("/").toString();
	}


	public void setRemoteInvocationFactoryRef(String remoteInvocationFactoryRef) {
		this.remoteInvocationFactoryRef = remoteInvocationFactoryRef;
	}

	@Override
	protected BeanDefinition prepareBeanDefinition(Class<?> serviceInterface, String beanName, String serviceName) {
		GenericBeanDefinition beanDef = new GenericBeanDefinition();
		beanDef.setBeanClass(RmiProxyFactoryBean.class);

		MutablePropertyValues values = new MutablePropertyValues();
		values.addPropertyValue("serviceUrl", getRmiUrl() + serviceName);
		values.addPropertyValue("serviceInterface", serviceInterface);
		values.addPropertyValue("remoteInvocationFactory", new RuntimeBeanReference(remoteInvocationFactoryRef));

		beanDef.setPropertyValues(values);

		logger.debug("praparing bean definition for ['" + serviceInterface.getName() + "']");

		return beanDef;
	}

	@Override
	protected String prepareBeanId(Class<?> serviceInterface, String beanName) {
		return "rmfb#" + beanName;
	}

	
}
